import Base from "../base.js";
import usersService from "../../service/usersService.js";
export default class extends Base {

  constructor(props) {
    super(props);

  }

  //渲染页面
  render() {
    const template = `
    <form class="layui-form" action="" style="width:400px">
      <div class="layui-form-item addUser" style="height:100px">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>新增用户</legend>
        </fieldset>
            <label class="layui-form-label">用户账号</label>
            <div class="layui-input-inline">
            <input type="text" name="username" required  lay-verify="required" placeholder="请输入账号" autocomplete="off" class="layui-input">
            <span></span>
            </div>
      </div>
      <div class="layui-form-item addUser">
          <label class="layui-form-label">用户密码</label>
          <div class="layui-input-inline">
          <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
          </div>
      </div>
      <div class="layui-form-item">
          <div class="layui-input-block">
          <button class="layui-btn saveBtn" lay-submit lay-filter="saveBtn" type="button">保存</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
          </div>
      </div>
    </form>
        `
    this.$el.html(template);

  }

  //交互
  handle() {
    const that = this;
    this.form.on("submit(saveBtn)", function (data) {//保存按钮事件
      that.createUsers(data.field);
      $(".addUser input[name=username]").val("");
      $(".addUser input[name=password]").val("");
      layer.msg("新增成功！");
    });

    //用户账号密码框聚焦事件,把账号密码框内容清空
    $(".addUser input[name=username]").on("focusin",e=>{
      $(".addUser input[name=username]").val("");
      $(".addUser input[name=password]").val("");
    })
    //用户账号框失焦事件
    $(".addUser input[name=username]").on("blur", async e => {
      const username = $(".addUser input[name=username]").val();
      const status = await that.isUse(username)
          if (status) {
            $(".addUser span").html("用户账号已存在");
            $(".addUser span").css({ "color": "red" })
            $(".saveBtn").prop("disabled", true);
            } else {
                $(".addUser span").html("用户账号可使用");
                $(".addUser span").css({ "color": "green" })
                $(".saveBtn").prop("disabled", false);
            }
    })
  }

  //新增学生的方法
  async createUsers(user) {
    await usersService.create(user);
  }

  //验证用户账号的方法
  async isUse(username){
   const status= await usersService.isUse(username);
   return status;
  }
}